import re
from itertools import combinations

import jieba
import requests
from bs4 import BeautifulSoup
from sortedcollections import OrderedSet

from config import avpair_url, api_key, ment2ent_url, NAMES
from find_syn_by_baike import find_syn_by_baidubaike, find_syn_by_hudongbaike
from translate import translate_en, translate_zh, translate

english_word_pat = re.compile(r'^[a-zA-Z0-9 ,.?:\(\)]+$')


def is_english_word(w):
    return english_word_pat.match(w) is not None


chinese_word_pat = re.compile(r'^[\u4e00-\u9fa50-9 ，。？：（）]+$')


def is_chinese_word(w):
    return chinese_word_pat.match(w) is not None


space_split_pat = re.compile(r"\s+")


def space_split(w):
    return space_split_pat.split(w)


def find_abbr_by_trans(w, mode='auto'):
    '''
    # print(find_abbr_by_trans('我爱你呀'))
    # print(find_abbr_by_trans('北京大学'))
    # print(find_abbr_by_trans('Bei Jing '))
    # print(find_abbr_by_trans('bei jing '))
    print(find_abbr_by_trans('bei Jing '))
    print(find_abbr_by_trans('bei Jing '))
    '''

    def cmp_abbr_zh(w, mode='auto'):
        res = set()
        # 长度大于2，小于单词本身长度
        if mode == 'auto':
            if len(w) <= 5:
                mode = 'full'
            else:
                mode = 'fast'

        if mode == 'full':
            for length in range(2, min(4, len(w))):
                for c in combinations(w, length):
                    c = ''.join(c)
                    res.add(c)
            return res
        elif mode == 'fast':
            ls = list(jieba.cut(w))
            w = "".join([w[0] for w in ls if len(w) >= 1])
            res.add(w)
            if len(ls) >= 1:
                res.add("".join([ls[0]] + [w[0] for w in ls[1:]]))
            return res
        else:
            raise ValueError('mode={} not support'.format(mode))


    def cmp_abbr_en(exp):
        res = []
        for w in space_split(exp):
            if w:
                res.append(w[0])
        return [''.join(res)]

    def get_cmp_word(w):
        if is_english_word(w):
            return cmp_abbr_en(w), 'en', 'zh'
        else:
            return cmp_abbr_zh(w, mode), 'zh', 'en'

    cmp_words, fromLang, toLang = get_cmp_word(w)

    res = []
    t = translate(w, fromLang=fromLang, toLang=toLang).strip().lower()
    for cmp_word in cmp_words:
        trans_cmp = translate(cmp_word, fromLang=fromLang, toLang=toLang).strip().lower()
        if trans_cmp == t:
            res.append(cmp_word)
    return res


def find_syn_by_round_trans(q):
    '''
    q = "龟头包皮炎"
    print(find_syn_by_round_trans(q))
    q = 'Glans penis foreskin'
    print(find_syn_by_round_trans(q))
    '''
    if is_english_word(q):
        first_trans, sencond_trans = translate_en, translate_zh
    else:
        first_trans, sencond_trans = translate_zh, translate_en

    res = OrderedSet()
    while q not in res and len(res) < 10:
        res.add(q)
        qt = first_trans(q)
        res.add(qt)
        q = sencond_trans(qt)
    res = list(res)
    return res


def find_syn_by_ment2ent(q):
    r = requests.get(ment2ent_url.format(q, api_key))
    # {'status': 'ok', 'ret': ['支气管炎']}
    return set(r.json()['ret'])


pats = [re.compile(r"\s*" + r"\s*".join(n) + r"\s*") for n in NAMES]


def find_syn_by_avpair(q):
    res = set()
    r = requests.get(avpair_url.format(q, api_key))
    rjson = r.json()
    # {'status': 'ok', 'ret': [['英文名称', 'bronchitis'], ['就诊科室', '呼吸科']
    for r in rjson['ret']:
        p, o = r
        p = BeautifulSoup(p, 'lxml').get_text()
        for pat in pats:
            if pat.match(p):
                res.add(o)
    res = list(res)
    return res


from read_data import SYN_DICT
def find_syn_by_hit(w):
    return list(SYN_DICT.get(w, set()))




def find_syn(w):
    res = {}
    w = w.strip()
    if w:
        res.update({"abbr": find_abbr_by_trans(w)})
        res.update({"round_trans": find_syn_by_round_trans(w)})
        res.update({"ment2ent": find_syn_by_ment2ent(w)})
        res.update({"avpair": find_syn_by_avpair(w)})
        res.update({"hit": find_syn_by_hit(w)})
        res.update({"hudongbaike": find_syn_by_hudongbaike(w)})
        res.update({"baidubaike": find_syn_by_baidubaike(w)})
    return res


if __name__ == "__main__":
    data = []
    for word in ['复旦', '复旦大学', '慢支', '慢性支气管炎', '老婆', '妻子']:
        res = find_syn(word)
        res["input_word"] = word
        from pprint import pprint
        pprint(res)
        data.append(res)

    # import pandas as pd
    #
    # df = pd.DataFrame(data=data)
    # df.to_excel("tmp.xlsx")







